package org.eden.heartbeat.core.ping.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eden.heartbeat.api.model.MachineInfo;
import org.eden.heartbeat.core.ping.PingService;
import org.eden.heartbeat.core.ping.PingServiceAdmin;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * Ping service implementation using the java socket technology.
 *
 * @author trsimoes
 * @version $Revision:$
 */
public class SocketPingServiceImpl implements PingService, PingServiceAdmin {

    private static Log LOG = LogFactory.getLog(SocketPingServiceImpl.class);

    private String host;
    private int port;
    private int timeout;
    private SocketAddress address;

    public SocketPingServiceImpl(final MachineInfo machineInfo) {
        this.host = machineInfo.getHost();
        this.port = machineInfo.getPort();
        this.timeout = machineInfo.getTimeout();
        this.address = new InetSocketAddress(this.host, this.port);
    }

    @Override
    public boolean ping() {

        Socket pingSocket = new Socket();
        final long start = System.currentTimeMillis();
        try {
            pingSocket.connect(address, timeout);
        } catch (IOException e) {
            return false;
        } finally {
            final long end = System.currentTimeMillis();
            if (LOG.isTraceEnabled()) {
                LOG.trace("ping duration: " + (end - start) + "ms");
            }
        }

        return true;
    }

    @Override
    public void reloadConfigurations(final MachineInfo machineInfo) {
        this.host = machineInfo.getHost();
        this.port = machineInfo.getPort();
        this.timeout = machineInfo.getTimeout();
        this.address = new InetSocketAddress(host, port);
    }
}